package controller;

import graphical.fatclient.Mainwindow;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Bulldozer extends AbstractHandler {

	private static final Logger logger = LoggerFactory
			.getLogger(Bulldozer.class);
	private static final int FAT_CLIENT = 0;
	private static final int WEB_INTERFACE = 1;
	
	public static void main(String args[]) {
		// to modify to change the interface
		int CONFIG = FAT_CLIENT;
		
		switch (CONFIG) {
		case (FAT_CLIENT):
			logger.info("Graphical interface launched!");
			launchFatclient(args);
			break;
		case (WEB_INTERFACE):
			logger.info("Trying to launch server...");
			launchServer();
			logger.info("... Success!");
			break;
		}
	}

	private static void launchFatclient(String[] args) {
			Mainwindow.launchWindow();
	}
	
	private static void launchServer() {
		Server server = new Server(8080);
		server.setHandler(new Bulldozer());

		try {
			server.start();
			server.join();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void handle(String target,
			Request baseRequest,
			HttpServletRequest request,
			HttpServletResponse response) 
					throws IOException, ServletException {

		response.setContentType("text/html;charset=utf-8");
		response.setStatus(HttpServletResponse.SC_OK);
		baseRequest.setHandled(true);
		response.getWriter().println("<h1>Hello World</h1>");
		response.getWriter().println("<p>Jetty Server is working on "+baseRequest.getLocalAddr()+":"+baseRequest.getLocalPort());
	}
}
